package com.newsvoice.activity;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.rssreader.playtts.ShowExtractedArticle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.Toast;

public class ShowNewsActivity extends DashBoardActivity implements
		ICallbackHandler {
	private ListAdapter adapter;
	private String category = null;
	private ListView listView;
	private List<JSONObject> objects = null;
	private boolean reloadFlag = false;
	private Button addNews;
	public static ProgressDialog dialog;

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		System.out.println("oncreate");
		setContentView(R.layout.news_list_shows);
		listView = (ListView) findViewById(R.id.article_list);
		category = getIntent().getStringExtra("category");
		setHeader("Tin Tức " + category, true, true, true, false);
		addNews = new Button(this);
		addNews.setText(R.string.addload_menu_item);
		addNews.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (Util.isNetworkAvailable(NewsVoiceApplication.getInstance()
						.getApplicationContext())) {
					NewsVoiceApplication.getInstance();
					Integer offset = NewsVoiceApplication.getOffsetCache().get(
							category + "offset");
					offset += 10;
					NewsVoiceApplication.getInstance();
					NewsVoiceApplication.getOffsetCache().put(
							category + "offset", offset);
					loadNews(category, offset);
				} else {
					Toast.makeText(
							NewsVoiceApplication.getInstance()
									.getApplicationContext(), "no internet",
							Toast.LENGTH_SHORT).show();
				}
			}
		});
		listView.addFooterView(addNews);
		// adapter = this.getListAdapter();
		NewsVoiceApplication.getInstance();
		objects = (List<JSONObject>) NewsVoiceApplication.getAdaptersCache()
				.get(category);

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				JSONObject json = (JSONObject) adapter.getItem(arg2);
				try {
					URL url = (URL) json.get("url");
					// Intent browserIntent = new
					// Intent(Intent.ACTION_VIEW,
					// Uri.parse(url.toString()));
					// startActivity(browserIntent);
					Intent i1 = new Intent(getApplicationContext(),
							ShowExtractedArticle.class);
					i1.putExtra("urlString", url.toString());
					i1.putExtra("title", json.get("title").toString());
					startActivity(i1);

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		});

		if (objects == null) {
			if (Util.isNetworkAvailable(this)) {
				NewsVoiceApplication.getInstance();
				NewsVoiceApplication.getOffsetCache().put(category + "offset",
						Integer.valueOf(0));
				loadNews(category, 0);
				System.out.println("conneting internet");
			} else {
				Toast.makeText(getApplicationContext(), "no internet",
						Toast.LENGTH_SHORT).show();
			}
		} else {
			adapter = new RssListAdapter(this, objects);
			listView.setAdapter(adapter);
		}
	}

	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
		super.onSaveInstanceState(savedInstanceState);
		// Save UI state changes to the savedInstanceState.
		// This bundle will be passed to onCreate if the process is
		// killed and restarted.
		savedInstanceState.putBoolean("MyBoolean", true);
		savedInstanceState.putDouble("myDouble", 1.9);
		savedInstanceState.putInt("MyInt", 1);
		savedInstanceState.putString("MyString", "Welcome back to Android");
		// etc.
	}

	@Override
	public void response(String response) {
		Log.d("callMethod", response);
		/*
		 * try { JSONObject jso = new JSONObject(response); JSONArray ja =
		 * jso.getJSONArray("article"); List<Article> msg = new
		 * ArrayList<Article>(); for (int i = 0; i < ja.length(); i++) { Article
		 * m = new Article(); JSONObject jsonMsg = ja.getJSONObject(i);
		 * m.setArticleId(Long.valueOf(jsonMsg.getString("articleId")));
		 * m.setDescription(jsonMsg.getString("description"));
		 * m.setFeedId(Long.valueOf(jsonMsg.getString("feedId")));
		 * m.setImgLink(jsonMsg.getString("imgLink"));
		 * m.setPubDate(jsonMsg.getString("pubDate"));
		 * m.setTitle(jsonMsg.getString("title")); m.setUrl(new
		 * URL(jsonMsg.getString("url"))); msg.add(m); }
		 */
		if (objects == null || reloadFlag) {
			objects = new ArrayList<JSONObject>();
			reloadFlag = false;
		}

		int previousPosition = objects.size();
		objects.addAll(Util.convertToJSONObjects(response));
		adapter = new RssListAdapter(this, objects);

		listView.setAdapter(adapter);
		listView.setSelection(previousPosition);

		/*
		 * } catch (Exception e) { Log.d("Error: ", "Processing of " +
		 * response); if (e != null && e.getMessage() != null) Log.d("Error: ",
		 * e.getMessage()); else if (e != null) Log.d("Error: ", e.toString());
		 * else Log.d("Error: ", "Null Exception"); }
		 */}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		NewsVoiceApplication.getInstance().getAdaptersCache()
				.put(category, objects);
		System.out.println("onpause");
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (dialog != null && dialog.isShowing()) {
			dialog.dismiss();
			dialog = null;
		}

		System.out.println("ondestroy");
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.news_list_shows_options, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.reload_menu_item:
			if (Util.isNetworkAvailable(this)) {
				NewsVoiceApplication.getInstance();
				NewsVoiceApplication.getOffsetCache()
						.put(category + "offset", 0);
				reloadFlag = true;
				loadNews(category, 0);
			} else {
				Toast.makeText(this, "no internet", Toast.LENGTH_SHORT).show();
			}
			break;
		case R.id.addload_menu_item:
			if (Util.isNetworkAvailable(this)) {
				NewsVoiceApplication.getInstance();
				Integer offset = NewsVoiceApplication
						.getOffsetCache().get(category + "offset");
				offset += 10;
				NewsVoiceApplication.getInstance();
				NewsVoiceApplication.getOffsetCache()
						.put(category + "offset", offset);
				loadNews(category, offset);
			} else {
				Toast.makeText(this, "no internet", Toast.LENGTH_SHORT).show();
			}
			break;

		default:
			break;
		}

		return true;
	}

	private void loadNews(String category, int offset) {
		Map<String, String> params = new HashMap<String, String>();
		params.put("category", category);
		params.put("offset", String.valueOf(offset));
		callWebService(params);

	}

	private void callWebService(Map<String, String> params) {
		WebService webService = new WebService(
				"http://192.168.5.1:8080/VoiceNewsServer/rest/services/",
				"articles", params, this, WebService.GET_METHOD, this);
		webService.execute();
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		System.out.println("onrestart");
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		System.out.println("onresume");
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		System.out.println("onstart");

	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		System.out.println("onstop");
	}

	@Override
	public void btnRefreshClick(View v) {
		// TODO Auto-generated method stub
		if (Util.isNetworkAvailable(this)) {
			NewsVoiceApplication.getInstance();
			NewsVoiceApplication.getOffsetCache()
					.put(category + "offset", 0);
			reloadFlag = true;
			loadNews(category, 0);
		} else {
			Toast.makeText(this, "no internet", Toast.LENGTH_SHORT).show();
		}
	}

}
